package com.sztu.service;

import com.sztu.mapper.BorrowMapper;
import com.sztu.pojo.Borrow;
import com.sztu.utils.LongUtil;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

@Service
public class BorrowServiceImpl implements BorrowService {
    private final BorrowMapper borrowMapper;

    private final DeviceService deviceService;

    public BorrowServiceImpl(BorrowMapper borrowMapper, DeviceService deviceService) {
        this.borrowMapper = borrowMapper;
        this.deviceService = deviceService;
    }


    @Override
    public void borrow(Map<String, Object> borrowInfo) throws Exception {
        if(!deviceService.canBeBorrowed(LongUtil.parseLong(borrowInfo.getOrDefault("device_id",0L)))) throw new Exception("已经被借用过了");
        Borrow borrow=new Borrow()
                .setDeviceId(LongUtil.parseLong(borrowInfo.getOrDefault("device_id",0L)))
                .setUserId(LongUtil.parseLong(borrowInfo.getOrDefault("user_id",0L)))
                .setApproveUserId(LongUtil.parseLong(borrowInfo.getOrDefault("principal_id",0L)))
                .setApproveResult(false)
                .setIsReturn(false);
        borrowMapper.insert(borrow);
    }

    @Override
    public void approve(Map<String, Object> approveInfo) {
        Long deviceId=LongUtil.parseLong(approveInfo.getOrDefault("device_id",0L));
        Borrow borrow=new Borrow()
                .setId(LongUtil.parseLong(approveInfo.getOrDefault("id",0L)))
                .setApproveResult((Boolean) approveInfo.getOrDefault("approve_result",false))
                .setApproveText((String) approveInfo.getOrDefault("approve_text",null))
                .setUseDate(new Timestamp(System.currentTimeMillis()))
                ;
        borrowMapper.updateById(borrow);
        if((Boolean) approveInfo.getOrDefault("approve_result",false)){
            deviceService.setDeviceState(deviceId,5L);
        }else{
            deviceService.setDeviceState(deviceId,4L);
        }
    }


    @Override
    public void returnDevice(Map<String,Object> returnInfo) {
        Long deviceId=LongUtil.parseLong(returnInfo.getOrDefault("device_id",0L));
        Borrow borrow=new Borrow()
                .setId(LongUtil.parseLong(returnInfo.getOrDefault("id",0L)))
                .setIsReturn((Boolean) returnInfo.getOrDefault("is_return",null))
                ;
        borrowMapper.updateById(borrow);
        if((Boolean) returnInfo.getOrDefault("is_return",null)){
            deviceService.setDeviceState(deviceId,4L);
        }else{
            deviceService.setDeviceState(deviceId,5L);
        }
    }

    @Override
    public List<Map<String, Object>> getNeedsApprove(Long UserId) {
        return borrowMapper.getApproveInfoByUserId(UserId);
    }

    @Override
    public List<Map<String, Object>> getApprovals(Long UserId) {
        return borrowMapper.getApprovalsByUserId(UserId);
    }


}
